<?php
namespace app\api\controller\vppz;


use addons\message\model\MessageNotice;
use addons\message\model\MessageUser;
use app\admin\controller\vppz\VipCard;
use app\admin\model\vppz\VipOrder;
use app\admin\model\vppz\VipPackage;
use think\Cache;
use think\Db;

use \app\admin\model\vppz\User as UserModel;
use \app\admin\model\vppz\Staff as StaffModel;
use \app\admin\model\vppz\Order as OrderModel;
use \app\admin\model\vppz\Client as ClientModel;
use app\admin\model\vppz\App as AppModel;

use \addons\vppz\library\Vpower;


class User extends App
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize(){
        parent::_initialize();

		$this->UserModel = new UserModel;
		$this->StaffModel = new StaffModel;
		$this->OrderModel = new OrderModel;
		$this->ClientModel = new ClientModel;
        $this->messageModel = new MessageUser();
    }


    /**
     * 服务下单页
     */
    public function index(){
		//$area=$this->_area;// 用户控制器不区分运营区域
		$mine=$this->_mine;

		$statistic=array();
		// 待支付
		$statistic['topays'] = $this->OrderModel->where(['app_id'=>$this->app_id,'user_id'=>$mine['id'],'status'=>10])->count();
		// 待服务
		$statistic['todos'] = $this->OrderModel->where(['app_id'=>$this->app_id,'user_id'=>$mine['id'],'status'=>20])->count();

		// 获取我的服务员身份信息
		$staff = $this->StaffModel->where(['app_id'=>$this->app_id,'user_id'=>$mine['id']])->find();
        //未读消息
        $message = $this->messageModel->where(['user_id'=>$mine['id'],'is_see'=>0])->count();
		$this->success('',array(
			'now'=>time(),
			'mine'=>$mine,
            'message'=>$message,
			'statistic'=>$statistic,
			'staff'=>$staff
		));
    }
    public function gowxLogin(){
        $input = input();
        $code = isset($input['code']) ? $input['code'] : '';
        if (empty($code)) {
            echo json_encode(['success' => false, 'message' => '参数不完整']);
            exit;
        }
        // 配置参数
        $AppModel = new AppModel;
        $app = $AppModel->find($this->app_id);
        $appid = $app['wxapp_id'];
        $secret = $app['wxapp_secret'];
        // 1. 获取session_key
        $session_key = \app\api\controller\Common::getSessionKey($appid, $secret, $code);
        \Tools::setValue('session_key',$session_key);
        $this->success('',array());
    }
    //解密手机号
    public function decodePhone(){
        header('Content-Type: application/json');
        // 配置参数
        $AppModel = new AppModel;
        $app = $AppModel->find($this->app_id);
        $appid = $app['wxapp_id'];
        $secret = $app['wxapp_secret'];
        // 获取POST数据
        $input = input();
        $code = isset($input['code']) ? $input['code'] : '';
        $encryptedData = isset($input['encryptedData']) ? $input['encryptedData'] : '';
        $iv = isset($input['iv']) ? $input['iv'] : '';

        // 验证参数
        if (empty($code) || empty($encryptedData) || empty($iv)) {
            echo json_encode(['success' => false, 'message' => '参数不完整']);
            exit;
        }

        // 1. 获取session_key
        $session_key = \Tools::getValue('session_key');
        if (!$session_key) {
            $this->error("获取session_key失败");
        }

        // 2. 解密手机号
        $phone_info = \app\api\controller\Common::decryptData($encryptedData, $iv, $session_key);
        if (!$phone_info) {
            $this->error("解密失败");
        }
        $this->success('',array(
			'success' => true,
            'phoneNumber' => $phone_info['phoneNumber'],
            'countryCode' => $phone_info['countryCode']
		));
    }
	// 用户个人资料修改
	public function profile(){
		//$area=$this->_area;// 用户控制器不区分运营区域
		$mine=$this->_mine;

		$submit = input('submit');

		if($submit=='save'){
			// 接受参数
			$avatar = input('avatar');
			$nickname = input('nickname');

			// 参数验证
			if(empty($avatar)){
				$this->error("请上传您的头像");
			}

			if(empty($nickname)){
				$this->error("请填写您的称呼");
			}
			if(mb_strlen($nickname)<2){
				$this->error("称呼至少2个字");
			}
			if(mb_strlen($nickname)>10){
				$this->error("称呼最多10个字");
			}

			/**
			if(empty($form['mobile'])){
				$this->error("请填写您的手机号");
			}
			**/

			// 修改
			$userUp=array(
				'nickname'=>$nickname,
				'avatar'=>$avatar,
				//'age'=>intval($form['age']),
				//'mobile'=>$form['mobile']
			);

			$ret = $this->UserModel->save($userUp,['id'=>$mine['id']]);
			if(!($ret>0)){
				$this->error("保存失败，请重试");
			}

			$this->success('保存成功');
		}
	}

	// 用户手机修改 TODO 目前并未做验证
	public function mobile(){
		//$area=$this->_area;// 用户控制器不区分运营区域
		$mine=$this->_mine;

		$submit = input('submit');

		if($submit=='save'){
			// 接受参数
			$mobile = input('mobile');

			// 参数验证
			if(empty($mobile)){
				$this->error("请填写您的手机号");
			}

			// 修改
			$userUp=array(
				'mobile'=>$mobile
			);

			$ret = $this->UserModel->save($userUp,['id'=>$mine['id']]);
			if(!($ret>0)){
				$this->error("保存失败，请重试");
			}

			$this->success('保存成功');
		}
	}

	// 更新前端用户信息
	public function update(){
		$mine=$this->_mine;
		$this->success('',['mine'=>$mine]);
	}


	// 服务对象管理
	public function clients(){
		$mine=$this->_mine;
		$clients = $this->ClientModel->where(['app_id'=>$this->app_id,'user_id'=>$mine['id']])->select();
		$this->success('',array('clients'=>$clients));
	}

	// 服务对象管理
	public function client(){
		$mine=$this->_mine;
		$submit = input('submit');
		if($submit=='save'){
			// 接受参数
			$form = input('form');
			if(empty($form)){
				$this->error("内容填写有误，请重试");
			}
			$form = json_decode(urldecode($form),true);
			if(!$form){
				$this->error("内容填写有误，请重试");
			}

			// 保存client
			// 去除client多余数据,添加client额外数据
			$client=array(
				'app_id'=>$this->app_id,
				'user_id'=>$mine['id'],
				'openid'=>$mine['openid'],
				'name'=>$form['name'],
				'sex'=>intval($form['sex']),
				'age'=>intval($form['age']),
				'mobile'=>$form['mobile'],
				//'idcard'=>$form['idcard']	保护隐私，暂不增加身份证号
			);

			$ret=$this->ClientModel->save($client);
			$client['id'] = $this->ClientModel->id;
			if(empty($ret) || empty($client['id'])){
				$this->error('服务器刚刚走神了，重试看看呢');
			}

			$this->success('新增成功');
		}else if('remove'==$submit){
			$id = input('id');
			if(!($id>0)){
				$this->error("请选择要移除的对象");
			}

			//ClientModel::destroy($id);
			Db::name('vppz_client')->where(['user_id'=>$mine['id'],'id'=>$id])->delete();

			$this->success('移除成功');
		}
	}
    public function kefu(){
        $accessToken = \Tools::getaccessToken(); // 通过微信API获取
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$accessToken;
        $openid = input('openid');
        $content = input('session_from');
        $nickname = input('nickname');
        //查询openid对应的用户是否是会员
        $user = $this->UserModel->where(['openid'=>$openid])->find();
        $vipMessageContent = 'ceshi';
        if(empty($user) === FALSE && $user['is_vip'] == 1){
            $order = VipOrder::where(['user_id'=>$user['id']])->find();
            if(empty($order) === FALSE){
                $package = VipPackage::where(['id'=>$order['package_id']])->find();
                $vipMessageContent = '您好！当前用户是'.$package['title'].'，有效期至'.$user['expire_time'].'。请提供优质服务！';
            }else{
                $vipMessageContent = '您好！当前用户是会员，有效期至'.$user['expire_time'].'。请提供优质服务！';
            }
            if(empty($nickname) === FALSE && $nickname !== 'undefined'){
                $content = "尊敬的会员:".$nickname."您好，有什么可以帮您？";
            }else{
                $content = "尊敬的会员您好，有什么可以帮您？";
            }
        }else{
            $vipMessageContent = `您好！当前用户是非会员。可向其介绍会员权益进行转化。`;
            if(empty($nickname) === FALSE && $nickname !== 'undefined'){
                $content = $nickname."您好，有什么可以帮您？";
            }else{
                $content = "您好，有什么可以帮您？";
            }
        }
        $data = array(
            'touser'=>$openid,
            'msgtype'=>'text',
            'text'=>array(
                'content'=>$content
            )
        );
        $headers = array(
            'Content-Type'=>'application/json; charset=utf-8'
        );
        $res = \Tools::curl($url,'POST',json_encode($data, JSON_UNESCAPED_UNICODE),$headers);

    }
}
